<template>
  <div class="card">
    <h2>登录</h2>
    <form @submit.prevent="submit">
      <input v-model="username" placeholder="用户名" />
      <input v-model="password" type="password" placeholder="密码" />
      <div v-if="username && !validUser" class="msg">用户名格式错误</div>
      <div v-if="password && !validPwd" class="msg">密码 6-16 位</div>
      <button type="submit" :disabled="!ok">立即登录</button>
    </form>
    <p v-if="err" class="err">{{ err }}</p>
    <router-link to="/register">账号需自行注册</router-link>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { getUsers, setCurrent } from '@/utils/storage'

const username = ref('')
const password = ref('')
const err = ref('')
const router = useRouter()

const validUser = computed(() => /^[a-zA-Z0-9]{3,12}$/.test(username.value))
const validPwd  = computed(() => password.value.length >= 6 && password.value.length <= 16)
const ok = computed(() => validUser.value && validPwd.value)

function submit() {
  const users = getUsers()
  if (!users[username.value]) { 
    err.value = '用户名不存在'
    return 
  }
  if (users[username.value] !== password.value) { 
    err.value = '密码错误'
    return 
  }

  setCurrent(username.value)
  router.push('/todo')
}
</script>

<style scoped src="@/assets/LoginView.css"></style>
